package com.cx.util.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.sun.org.apache.bcel.internal.generic.NEW;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.util.jdbc
 * @Description:
 * @Date 2025/6/5 9:28
 */

public class JDBCPoolUtils {

    static DataSource dataSource = null;

    //1.加载驱动 如果是mysql8.0以上版本，驱动需要加cj,如果是5版本，不需要加cj
    static {
        try {
            //读取配置文件
            Properties properties = new Properties();
            InputStream resourceAsStream = JDBCPoolUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(resourceAsStream);
            //获取连接对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            throw new RuntimeException(e+"配置文件加载失败");
        } catch (Exception e) {
            throw new RuntimeException(e+"数据库连接池加载失败");
        }
    }

   public static Connection getConnection() {
       //2.创建连接
       try {
           return dataSource.getConnection();
       } catch (SQLException e) {
           throw new RuntimeException(e+"数据库连接失败");
       }
   }

    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        //6.关闭资源
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e+"结果集关闭失败");
        }



    }

    public static void close(Connection connection, PreparedStatement preparedStatement) {
        //6.关闭资源
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e + "结果集关闭失败");
        }


    }



}